<script setup>
import { ref } from 'vue'
import useUserInfoStore from '@/stores/userInfo';
const userInfoStore = useUserInfoStore();
const userInfo = ref({ ...userInfoStore.info })

//定义数据模型
const pwdData = ref({
    oldPassword: '',
    newPassword: '',
    reNewPassword: ''
})

//清空数据
const clearPwdData = () => {
    pwdData.value = {
        oldPassword: '',
        newPassword: '',
        reNewPassword: ''
    }
}


//校验密码的函数
const checkRePassword = (rule, value, callback) => {
    if (value === '') {
        // callback(new Error('请再次确认密码'))
    } else if (value !== pwdData.value.newPassword) {
        callback(new Error('请确保两次输入的密码一样'))
    } else {
        callback();
    }
    return
}

//定义表单校验规则
const rules = {
    oldPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    reNewPassword: [
        {
            required: true,
            validator: checkRePassword,
            tigger: 'blur'
        }
    ]
}


//修改密码
import { userResetPasswordService } from '@/api/user.js'
import { ElMessage } from 'element-plus';
const resetPassword = async () => {
    //调用接口
    let result = await userResetPasswordService(pwdData.value);
    if(result.code === 0){
         ElMessage.success('重置密码成功')
        //修改pinia中的个人信息
        userInfoStore.setInfo(userInfo.value)
        clearPwdData()
    }else{
        ElMessage.error(result.msg ? result.msg : '重置密码失败')
    }
   
}

</script>


<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>重置密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-form :model="pwdData" :rules="rules" label-width="100px" size="large">
                    <el-form-item label="用户名">
                        <el-input v-model="userInfo.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="旧密码" prop="oldPassword">
                        <el-input v-model="pwdData.oldPassword" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword">
                        <el-input v-model="pwdData.newPassword" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="reNewPassword">
                        <el-input v-model="pwdData.reNewPassword" type="password"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="resetPassword">提交修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>